﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.ComponentModel.Composition;

using NuMetaheuristics.Genotypes;
using NuMetaheuristics.Operators.Vector;
using NuMetaheuristics.Operators.Value;

namespace NuMetaheuristics.Contexts.Vector.Double
{
    [DataContract(Namespace = "http://numetaheuristics.codeplex.com/schemas")]
    [Export(typeof(IContext<DoubleVectorGenotype>))]
    public class Linear : DoubleVectorContext, IDeserializationCallback
    {
        [DataMember]
        private DoubleVectorGenotype _weights;

        public Linear()
            : base()
        {
        }

        public Linear(int length)
            : base(length, 0.0, 1.0)
        {
            var weights = new DoubleVectorGenotype(_length + 1);
            _initializer.Operate(ref weights);
            _weights = weights;
        }

        override public void Evaluate(ref DoubleVectorGenotype genome)
        {
            double total = _weights.Vector[0];

            for(uint i = 0; i < genome.Vector.Length; i++)
            {
                total += (genome.Vector[i] * _weights.Vector[i+1]);
            }

            genome.Fitness = new FitnessSmallerIsBetter(total);
        }

        public void OnDeserialization(object sender)
        {
            var weights = new DoubleVectorGenotype(_length + 1);
            _initializer.Operate(ref weights);
            _weights = weights;
        }
    }
}
